class TreeNode {
  constructor(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
  }
}

/**
 * 入参为层序遍历，不存在的节点用null表示
 * 二叉树和层序有关的限制：i>=0，父节点是i，左节点是2i+1，右节点是2i+2
 * @param {*} array 
 * @returns 
 */
const ArrayToTreeNode = function(arr) {
  return createTreeNode(arr, 0);
}

function createTreeNode(arr, index) {
  if (index > arr.length || arr[index] == null) {
    return null;
  }
  const node = new TreeNode(arr[index]);
  node.left = createTreeNode(arr, index * 2 + 1);
  node.right = createTreeNode(arr, index * 2 + 2);
  return node;
}

module.exports = {
  TreeNode,
  ArrayToTreeNode
}
